package com.aide.security.auth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author 作者 : Administrator
 * @version 创建时间：2013-8-9 下午1:13:54
 * 
 *          类说明
 */
public class GetSNShell {

	/**
	 * 获取主板序列号
	 * 
	 * @return
	 */
	public static String getMotherboardSN() {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);

			String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
					+ "Set colItems = objWMIService.ExecQuery _ \n"
					+ "   (\"Select * from Win32_BaseBoard\") \n"
					+ "For Each objItem in colItems \n"
					+ "    Wscript.Echo objItem.SerialNumber \n"
					+ "    exit for  ' do the first cpu only! \n" + "Next \n";

			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}

	/**
	 * 获取硬盘序列号
	 * 
	 * @param drive
	 *            盘符
	 * @return
	 */
	public static String getHardDiskSN(String drive) {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);

			String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
					+ "Set colDrives = objFSO.Drives\n"
					+ "Set objDrive = colDrives.item(\""
					+ drive
					+ "\")\n"
					+ "Wscript.Echo objDrive.SerialNumber"; // see note
			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}

	/**
	 * 获取CPU序列号
	 * 
	 * @return
	 */
	public static String getCPUSerial() {
		String result = "";
		try {
			File file = File.createTempFile("tmp", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);
			String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
					+ "Set colItems = objWMIService.ExecQuery _ \n"
					+ "   (\"Select * from Win32_Processor\") \n"
					+ "For Each objItem in colItems \n"
					+ "    Wscript.Echo objItem.ProcessorId \n"
					+ "    exit for  ' do the first cpu only! \n" + "Next \n";

			// + "    exit for  \r\n" + "Next";
			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
			file.delete();
		} catch (Exception e) {
			e.fillInStackTrace();
		}
		if (result.trim().length() < 1 || result == null) {
			result = "无CPU_ID被读取";
		}
		return result.trim();
	}

	public static String getPhysicalAddress() {
		String os = System.getProperty("os.name").toLowerCase();
		if (!os.startsWith("windows")) {
			String mac = null;
			BufferedReader bufferedReader = null;
			Process process = null;
			try {
				process = Runtime.getRuntime().exec("ifconfig eth0");
				bufferedReader = new BufferedReader(new InputStreamReader(
						process.getInputStream()));
				String line = null;
				int index = -1;
				while ((line = bufferedReader.readLine()) != null) {
					index = line.toLowerCase().indexOf("hwaddr");
					if (index >= 0) {
						mac = line.substring(index + "hwaddr".length() + 1)
								.trim();
						return mac;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (bufferedReader != null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
			return "not";
		} else {
			try {
				Enumeration<NetworkInterface> ias = NetworkInterface
						.getNetworkInterfaces();
				StringBuffer sb = new StringBuffer();
				while (ias.hasMoreElements()) {
					NetworkInterface networkInterface = (NetworkInterface) ias
							.nextElement();
					if (networkInterface != null) {
						byte mac[] = networkInterface.getHardwareAddress();
						if (mac != null) {
							for (int i = 0; i < mac.length; i++) {
								if (i != 0)
									sb.append("-");
								String s = Integer.toHexString(mac[i] & 0xff);
								sb.append(s.length() != 1 ? s
										: (new StringBuilder(String.valueOf(0)))
												.append(s).toString());
							}
							if(sb.length()>0)
							sb.append(",");
						}
					}
				}
				String mac = sb.toString().toLowerCase();
				if (mac.endsWith(",")) {
					mac = mac.substring(0, mac.length() - 1);
				}
				return mac;
			} catch (Exception e) {
				e.printStackTrace();
				return "not";
			}
		}

	}

	public static void main(String[] args) {
		System.out.println("    MAC:" + GetSNShell.getPhysicalAddress());
		System.out.println("主板   SN:" + GetSNShell.getMotherboardSN());
		System.out.println("C盘     SN:" + GetSNShell.getHardDiskSN("c"));
		System.out.println("CPU  SN:" + GetSNShell.getCPUSerial());
	}
}
